<template>
	<view class="yyjl">
		<headertop title="用药记录" str1="oridei" :back1="back1"></headertop>
		<view class="yyjlback">

		</view>
		<view :style="{'margin-top':statusBarHeight+'px','width':'100%','height':barHeight+'px'}">
		</view>
		<view class="fenleiboxs" v-if="fenleiarr.length">
			<view :class="active==index?'itembox activecolor':'itembox'" @click="qiehuan(index)"
				v-for="(item,index) in fenleiarr" :key="index">
				<span>{{item['medicine_name']}}</span>
				<view class="actice" v-if="active==index">

				</view>
			</view>

		</view>
		<view class="msgicon" v-if="!fenleiarr.length">
			<image :src="_static('/images/wxnone.png')" mode="widthFix">
			</image>
			<view class="msgtext">
				暂无内容
			</view>
		</view>
		<view class="yybox" v-if="fenleiarr.length">
			<view class="center">
				<view class="topline">
					<view class="leftbox">
						<image :src="_static('/images/Group 11682@2x.png')" class="xbq" mode=""></image>
						<span>用药剂量统计</span>
						<span style="color:#86909C ;font-weight: 500;">（{{fenleiarr[active]['unit']}}）</span>
					</view>
					<view class="rightbtn">
						<view :class="mode=='week'?'btn1':'btn2'" @click="switchMode('week')">
							周
						</view>
						<view :class="mode=='month'?'btn1':'btn2'" @click="switchMode('month')">
							月
						</view>
					</view>
				</view>
				<view class="riqidate">
					<image @click="navigate(-1)" :src="_static('/images/you.png')" mode="" style="margin-left: 28rpx;">
					</image>
					<span>{{currentRange['start']}}至{{currentRange['end']}}</span>
					<image @click="navigate(1)" :src="_static('/images/zuo.png')" mode="" style="margin-right: 28rpx;">
					</image>
				</view>

				<view class="echarts">
					<l-echart ref="chartRef"></l-echart>
				</view>
			</view>
		</view>
		<view class="scfy" v-if="fenleiarr.length">
			上次服药日期：{{last_date}}
		</view>
	</view>
</template>
<script setup>
	const echarts = require('../../uni_modules/lime-echart/static/echarts.min');
	import headertop from '@/components/header.vue'
	import {
		_static
	} from '@/ulm/utils/url.js'
	import {
		ref,
		reactive,
		onMounted
	} from 'vue'
	import {
		onPageScroll,
		onLoad,
		onShow
	} from "@dcloudio/uni-app";
	import ulm, {
		$api
	} from '@/ulm';

	const mode = ref('week')
	// 当前基准日期
	const baseDate = ref(new Date())
	const statusBarHeight = ref('')
	const barHeight = ref('')
	const last_date = ref('')
	const chartRef = ref(null)
	const formData = reactive({
		medicine_id: '',
		start_time: '',
		end_time: ''
	})
	const fenleiarr = ref([])
	const active = ref(0)
	const optiondate = {
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'shadow'
			},
			confine: true
		},
		grid: {
			left: 0,
			right: 0,
			bottom: 15,
			top: 40,
			containLabel: true
		},
		textStyle: {
			fontSize: 8,
		},

		xAxis: {
			axisLabel: {
				show: true, // 确保显示标签
				interval: 0, // 强制显示所有标签
				fontSize: 10, // 调整字体大小
			},
			type: 'category',
			data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
		},
		yAxis: {
			type: 'value'
		},
		series: [{
			data: [150, 230, 224, 218, 135, 147, 260],
			type: 'line'
		}],
		dataZoom: [ // 数据区域缩放
			{
				type: 'inside',
				show: true,
				start: 0,
				end: 100,
				zoomLock: true
			},
		],

	}
	onLoad(() => {
		init()
	})

	function qiehuan(index) {
		if (active.value == index) return
		active.value = index
		medicineChartsinit()
	}
	// 切换模式
	const switchMode = (newMode) => {

		mode.value = newMode
		if (mode.value == 'week') {
			optiondate.dataZoom[0].end = 100
		} else {
			// uni.$uv.toast('左右滑动查看更多')
			uni.showToast({
				title: '左右滑动查看更多',
				icon: 'none'
			})
			optiondate.dataZoom[0].end = 20
		}
		baseDate.value = new Date() // 重置为当前日期
		medicineChartsinit()
	}
	// 导航到上一周期或下一周期
	const navigate = (direction) => {
		const newDate = new Date(baseDate.value)

		if (mode.value === 'week') {
			newDate.setDate(newDate.getDate() + direction * 7)
		} else {
			newDate.setMonth(newDate.getMonth() + direction)
		}
		console.log(newDate, 'newDatenewDatenewDatenewDate');
		if (mode.value === 'week') {
			console.log(getWeekRange(newDate), '171')
			if (convertToTimestamp(getWeekRange(newDate)['start']) > Date.now()) {
				return
			}
		} else {
			if (convertToTimestamp(getWeekRange(newDate)['start']) > Date.now()) {
				return
			}
		}
		baseDate.value = newDate
		medicineChartsinit()
	}

	function convertToTimestamp(dateStr) {
		return new Date(dateStr).getTime();
	}

	function padStart(n) {
		return n.toString().padStart(2, 0)
	}
	// 获取周的日期范围
	const getWeekRange = (date) => {
		const d = new Date(date)
		const day = d.getDay() // 0-6 (0是周日)

		// 计算周一
		const monday = new Date(d)
		monday.setDate(d.getDate() - (day === 0 ? 6 : day - 1))
		const year = monday.getFullYear()
		const month = padStart(monday.getMonth() + 1)
		const dayy = padStart(monday.getDate())
		var monday1 = `${year}-${month}-${dayy}`
		// 计算周日
		const sunday = new Date(monday)
		sunday.setDate(monday.getDate() + 6)

		const year1 = sunday.getFullYear()
		const month1 = padStart(sunday.getMonth() + 1)
		const day1 = padStart(sunday.getDate())
		var sunday1 = `${year1}-${month1}-${day1}`
		console.log(monday1, sunday1, 'monday1,sunday1monday1,sunday1monday1,sunday1');
		return {
			start: monday1,
			end: sunday1
		}
	}
	// 获取月的日期范围
	const getMonthRange = (date) => {
		const d = new Date(date)

		// 当月第一天
		const firstDay = new Date(d.getFullYear(), d.getMonth(), 1)
		const year = firstDay.getFullYear()
		const month = padStart(firstDay.getMonth() + 1)
		const dayy = padStart(firstDay.getDate())
		var firstDay1 = `${year}-${month}-${dayy}`
		// 当月最后一天
		const lastDay = new Date(d.getFullYear(), d.getMonth() + 1, 0)
		const year1 = lastDay.getFullYear()
		const month1 = padStart(lastDay.getMonth() + 1)
		const day1 = padStart(lastDay.getDate())
		var lastDay1 = `${year1}-${month1}-${day1}`

		return {
			start: firstDay1,
			end: lastDay1
		}
	}
	// 格式化日期
	const formatDate = (date, format = 'YYYY-MM-DD') => {
		const year = date.getFullYear()
		const month = String(date.getMonth() + 1).padStart(2, '0')
		const day = String(date.getDate()).padStart(2, '0')

		return format
			.replace('YYYY', year)
			.replace('MM', month)
			.replace('DD', day)
	}


	// 当前日期范围
	const currentRange = computed(() => {
		return mode.value === 'week' ?
			getWeekRange(baseDate.value) :
			getMonthRange(baseDate.value)
	})

	// 显示的日期范围文本
	const displayRange = computed(() => {
		const {
			start,
			end
		} = currentRange.value
		const startStr = formatDate(start)
		const endStr = formatDate(end)

		if (mode.value === 'week') {
			// 如果是同一月，只显示月份一次
			if (start.getMonth() === end.getMonth()) {
				return `${start.getMonth() + 1}月${start.getDate()}日-${end.getDate()}日`
			}
			return `${start.getMonth() + 1}月${start.getDate()}日-${end.getMonth() + 1}月${end.getDate()}日`
		} else {
			return `${start.getFullYear()}年${start.getMonth() + 1}月`
		}
	})


	async function init() {
		const res = await $api.myMedicine()
		if (res.code == 1) {
			fenleiarr.value = res.data
			if (res.data.length) {
				medicineChartsinit()
			}
		}
	}
	async function medicineChartsinit() {
		const {
			start,
			end
		} = currentRange.value
		formData['start_time'] = start
		formData['end_time'] = end
		formData['medicine_id'] = fenleiarr.value[active.value]['medicine_id']
		const res = await $api.medicineCharts(formData)
		if (res.code == 1) {
			optiondate.series[0]['data'] = res.data.dose_list
			optiondate.xAxis.data = res.data.date_list
			last_date.value = res.data.last_date
			setTimeout(async () => {
				if (!chartRef.value) return
				const myChart = await chartRef.value.init(echarts)
				myChart.setOption(optiondate)
			}, 500)
		}

	}
	onMounted(() => {
		statusBarHeight.value = uni.getSystemInfoSync().statusBarHeight
		const {
			top,
			height
		} = wx.getMenuButtonBoundingClientRect();
		barHeight.value = height ? height + (top - statusBarHeight.value) * 2 : 38;

	})
	onPageScroll((e) => {

		if (e.scrollTop > 100) {
			back1.value = '#81D6FF'
		} else {
			back1.value = ''
		}

	})
</script>


<style lang="scss">
	.msgicon {
		width: 608rpx;
		margin: 100rpx auto;
		overflow: hidden;

		.msgtext {
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			font-size: 28rpx;
			color: #86909C;
			text-align: center;
			width: 100%;
			margin-top: 30rpx;
		}

		image {
			width: 608rpx;
		}
	}

	page {
		background: #F7F8FA;
	}

	.yyjl {
		width: 100%;
		position: relative;
		overflow: hidden;

		.yyjlback {
			position: absolute;
			z-index: -1;
			width: 100%;
			height: 312rpx;
			background: linear-gradient(180deg, #CAEEFF 71%, rgba(240, 250, 255, 0) 100%);
			border-radius: 0rpx 0rpx 0rpx 0rpx;
		}

		.scfy {
			width: 686rpx;
			margin: auto;
			margin-top: 28rpx;
			height: 96rpx;
			display: flex;
			align-items: center;
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			font-size: 28rpx;
			color: #1D2129;
			box-shadow: 0rpx 4rpx 10rpx 0rpx rgba(0, 0, 0, 0.03);
			border-radius: 24rpx 24rpx 24rpx 24rpx;
			text-indent: 28rpx;
			background: #FFFFFF;
		}

		.yybox {
			width: 686rpx;
			margin: auto;
			margin-top: 32rpx;
			overflow: hidden;
			background: #FFFFFF;
			box-shadow: 0rpx 4rpx 10rpx 0rpx rgba(0, 0, 0, 0.03);
			border-radius: 24rpx 24rpx 24rpx 24rpx;
			padding: 26rpx 0;

			.center {
				width: 638rpx;
				margin: auto;

				.riqidate {
					width: 100%;
					height: 82rpx;
					background: rgba(203, 238, 255, 0.6);
					border-radius: 20rpx 20rpx 20rpx 20rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					font-size: 28rpx;
					color: #1D2129;
					margin: auto;
					margin-top: 24rpx;

					image {
						width: 32rpx;
						height: 32rpx;
					}

				}

				.echarts {
					width: 100%;
					margin-top: 32rpx;
					overflow: hidden;
				}

				.topline {
					width: 100%;
					display: flex;
					align-items: center;
					justify-content: space-between;

					.leftbox {
						display: flex;
						justify-content: space-between;
						align-items: center;
						font-family: PingFang SC, PingFang SC;
						font-weight: bold;
						font-size: 32rpx;
						color: #1D2129;

						.xbq {
							width: 34rpx;
							height: 20rpx;
							margin-right: 14rpx;
						}
					}

					.rightbtn {
						width: 182rpx;
						display: flex;
						align-items: center;
						background: #2AB4F5;
						height: 52rpx;
						border-radius: 8rpx 8rpx 8rpx 8rpx;

						.btn1 {
							width: 90rpx;
							height: 52rpx;
							background: #fff;
							border-radius: 8rpx 8rpx 8rpx 8rpx;
							border: 2rpx solid #2AB4F5;
							line-height: 52rpx;
							box-sizing: border-box;
							text-align: center;
							font-size: 32rpx;
							color: #2AB4F5;
						}

						.btn2 {
							font-family: PingFang SC, PingFang SC;
							font-weight: 400;
							font-size: 32rpx;
							color: #FFFFFF;
							line-height: 52rpx;
							width: 92rpx;
							text-align: center;
						}
					}
				}
			}
		}

		.fenleiboxs {
			width: 100%;
			margin-top: 16rpx;
			overflow-x: scroll;
			white-space: pre;

			.activecolor {
				font-weight: 500;
				font-size: 32rpx;
				color: #2AB4F5 !important;
			}

			.itembox {
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				font-size: 32rpx;
				color: #1D2129;
				display: inline-block;
				text-align: center;
				margin-left: 64rpx;
				height: 84rpx;
				line-height: 84rpx;
				position: relative;

				.actice {
					width: 48rpx;
					height: 4rpx;
					background: #2AB4F5;
					border-radius: 4rpx 4rpx 4rpx 4rpx;
					position: absolute;
					bottom: 0%;
					margin: auto;
					top: 0%;
					right: 0%;
					bottom: -90%;
					left: 0%;
				}
			}
		}
	}
</style>